import Taro from "@tarojs/taro";
import {WXUserinfo} from "@/utils/model";
import LocalData from "@/common/local_data";

class LocalUtils {
  static getLocalStorage(key: string) {
    const str = Taro.getStorageSync(key)
    if (!str) {
      return []
    }
    return JSON.parse(str)
  }

  //set
  static setLocalStorage(key: string, value: any) {
    let str = value;
    if (typeof value !== 'string') {
      str = JSON.stringify(value)
    }
    Taro.setStorageSync(key, str)
  }

  static getLocalStr(key: string) {
    return Taro.getStorageSync(key);
  }

  //set
  static setLocalStr(key: string, value: any) {
    Taro.setStorageSync(key, value)
  }

  static removeLocalStorage(key: string) {
    Taro.removeStorageSync(key)
  }

  static getUserinfo(): WXUserinfo {
    const nickname = Taro.getStorageSync('nickname')
    const avatar = Taro.getStorageSync('avatarUrl')
    return {
      nickname, avatar
    }
  }

  static setUserinfo(nickname, avatarUrl) {
    LocalUtils.setLocalStr('nickname', nickname)
    LocalUtils.setLocalStr('avatarUrl', avatarUrl)
  }

  static getToken(): string {
    return LocalUtils.getLocalStr(LocalData.token);
  }

  static setToken(token: string) {
    LocalUtils.setLocalStr(LocalData.token, token);
  }


  static getUserId(): string {
    return LocalUtils.getLocalStr(LocalData.userId);
  }

  static exitLogin() {
    LocalUtils.removeLocalStorage(LocalData.token);
  }


}

export default LocalUtils
